import {
  LockOutlined,
  MobileOutlined,
} from '@ant-design/icons';
import { Alert, Space, message, Tabs } from 'antd';
import React, { useState } from 'react';
import ProForm, {ProFormCaptcha, ProFormCheckbox, ProFormText, ProFormTextArea, ProFormRadio} from '@ant-design/pro-form';
import { useIntl, Link, history, FormattedMessage, SelectLang, useModel } from 'umi';
import Footer from '@/components/Footer';
import { login } from '@/services/doa/user';
import styles from './index.less';
import crypto from "@/encrypt/Crypto";
import BDStorageUtils from '@/utils/BDStorageUtils'
import NetworkCardSetting from '@/components/RightContent/NetworkCardSetting';


const LoginMessage = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login = () => {


  const getLoginRole = ()=>{
    const url = history.location.pathname
    return url.replace("/user/login/","").replace("/user/login","")
  }

  const [submitting, setSubmitting] = useState(false);
  const [userLoginState, setUserLoginState] = useState({});
  const [type, setType] = useState(getLoginRole());
  const { initialState, setInitialState } = useModel('@@initialState');
  const intl = useIntl();

  console.log("===type: " + type)


  const getDefaultUser = () => {
    if(type === "grs"){
      return "admin"
    }
    if(type === "irs"){
      return "aibd/dou.ADMIN"
    }
    if(type === "registry" || type === "repository" || type === "normal"){
      return "aibd/dou.liuyi"
    }
    return "admin"
  }

  //登陆成功后，获取用户信息,data中为token和doi值，暂时未做持久化存储
  const fetchUserInfo = async (data) => {
    console.log("====fetchUserInfo====")
    console.log(data)
    console.log(initialState)
    console.log(initialState?.fetchUserInfo)
    const userInfo = await initialState?.fetchUserInfo({doi:data?.doi, role:data?.role});
    console.log(userInfo)
    if (userInfo) {
      BDStorageUtils.saveUsers({...data,access:JSON.parse(userInfo)?.handleValues?.access})
      await setInitialState((s) => ({ ...s, currentUser: {...(JSON.parse(userInfo)), access:JSON.parse(userInfo)?.handleValues?.access }}));
    }
  };

  const handleSubmit = async (values) => {

    if(values.role == null){
      values.role = type
    }
    console.log(values)
    setSubmitting(true);
    try {
      // 登录
      const jws = await crypto.sign("hello", values.key)
      const data = {"doi":values.doi, "token":jws, role:values.role}
      console.log(data)
      const msg = await login(data);
      console.log(msg)

      if (msg.success === true) {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        console.log("get current user with: ")
        console.log(data)
        await fetchUserInfo(data);
        /** 此方法会跳转到 redirect 参数所在的位置 */

        if (!history) return;
        const { query } = history.location;
        const { redirect } = query;
        history.push(redirect || '/');
        return;
      } // 如果失败去设置用户错误信息

      setUserLoginState(msg);
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      message.error(defaultLoginFailureMessage);
    }

    setSubmitting(false);
  };

  const { status, type: loginType } = userLoginState;
  return (
    <div className={styles.container}>
      <div className={styles.lang} data-lang>
        <NetworkCardSetting />
        {SelectLang && <SelectLang />}
      </div>
      <div className={styles.content}>
        <div className={styles.top}>
          <div className={styles.header}>
            <Link to="/">
              {/*<img alt="logo" className={styles.logo} src="/logo-1.png" />*/}
              <span className={styles.title}>数联网系统</span>
            </Link>
          </div>
          <div className={styles.desc}>
            {intl.formatMessage({
              id: 'pages.layouts.userLayout.title',
            })}
          </div>
        </div>

        <div className={styles.main}>
          <ProForm
            initialValues={{
              autoLogin: true,
              doi: getDefaultUser(),
              role:"repository",
              key:'{"kty":"EC","d":"koiB0_ffLlbOwxydk9yjXjwaNq-wYLq6QO1Ee9g94-I","use":"sig","crv":"P-256","kid":"123456","x":"7MTAnpNwyPnTTe54C0rtPB28OyZ1ZZz87VFqil3t59s","y":"l72E_htBfwUXVAqF9De6yr_s9fr9Hp9v3d3ArssI_dk","alg":"ES256"}',
            }}
            submitter={{
              searchConfig: {
                submitText: intl.formatMessage({
                  id: 'pages.login.submit',
                  defaultMessage: '   登录',
                }),
              },
              render: (_, dom) => dom.pop(),
              submitButtonProps: {
                loading: submitting,
                size: 'large',
                style: {
                  width: '100%',
                },
              },
            }}
            onFinish={async (values) => {
              handleSubmit(values);
            }}
          >
            {
              <>
                {type === "" ?
                  <ProFormRadio.Group
                  name="role"
                  radioType="button"
                  options={[
                    {
                      label: '标识注册系统',
                      value: 'irs',
                    },
                    {
                      label: '仓库系统',
                      value: 'repository',
                    },
                    {
                      label: '注册表系统',
                      value: 'registry',
                    },
                    {
                      label: '普通用户',
                      value: 'normal',
                    },
                  ]}
                /> : null
                }
                <ProFormText
                  fieldProps={{
                    size: 'large',
                    prefix: <MobileOutlined className={styles.prefixIcon} />,
                  }}
                  name="doi"
                  placeholder={intl.formatMessage({
                    id: 'pages.login.SecretLogin.doi',
                    defaultMessage: '用户标识',
                  })}
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.doi.required"
                          defaultMessage="请输入用户标识"
                        />
                      ),
                    }
                  ]}
                />
                <ProFormTextArea
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={intl.formatMessage({
                    id: 'pages.login.SecretLogin.key',
                    defaultMessage: '请输入用户密钥',
                  })}
                  name="key"
                  autoSize={true}
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.key.required"
                          defaultMessage="请输入密钥信息！"
                        />
                      ),
                    },
                  ]}
                />
              </>
            }
            <div
              style={{
                marginBottom: 24,
                float: 'right',
              }}
            >
              <ProFormCheckbox noStyle name="autoLogin">
                <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录" />
              </ProFormCheckbox>
              <Link to="/user/register">
                <span>注册账号</span>
              </Link>
            </div>
          </ProForm>
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
